package pri.zxx.webdemo.utils;

import lombok.experimental.UtilityClass;
import org.slf4j.MDC;

import java.util.Objects;
import java.util.UUID;

/**
 * logback的工具
 *
 * @author wangn <15124178@qq.com> 2020/7/15
 */
@UtilityClass
public class MDCUtil {
    /**
     * 全局RequestId的命名
     */
    public final String REQUEST_ID = "Request-Id";

    /**
     * 获取请求ID
     *
     * @return
     */
    private String getRequestId() {
        return MDC.get(REQUEST_ID);
    }

    /**
     * 获取请求ID
     *
     * @return
     */
    public String initRequestId() {
        if (Objects.isNull(getRequestId())) {
            setRequestId(UUID.randomUUID().toString().replaceAll("-", ""));
        }
        return getRequestId();
    }

    /**
     * 设置
     *
     * @param requestId
     */
    public void setRequestId(String requestId) {
        MDC.put(REQUEST_ID, requestId);
    }

    public static void removeRequestId() {
        MDC.remove(REQUEST_ID);
    }
}
